#加载R包
library(openxlsx)
library(writexl)
library(readr)
library(tidyverse)
library(Biobase)

#加载地址
setwd("C:/Users/15791/Documents/Rshijian3/RNAseq_Data")

#读取文件进入R环境
clin_inf <- read.table("clin_inf.csv",header = TRUE)
count <- read.table("count.csv",header = TRUE)
exp_inf <- read.table("exp_inf.csv",header = TRUE)
ID_annoation <- read.table("ID_annoation.csv",header = TRUE)

#数据处理
# 1.按照行合并
clin_exp_inf <- merge(clin_inf,exp_inf,by="样本名称")
clin_exp_inf <- column_to_rownames(clin_exp_inf, "样本名称")

# 2.删除多余的字母
colnames(count) <- sub(".$","",colnames(count)) # 删除最后一个字母

# 3.改变行名为基因ID名字
count <- column_to_rownames(count, "gene_i")

# 4.改变不规范的内容
colnames(count) <- sub("X(...$)","PTB\\1",colnames(count))
colnames(count) <- sub("X","XYA",colnames(count))
ID_annoation$gene_id <- gsub("\\..*","",ID_annoation$gene_id) # 小数变为整数
count <- count[,match(rownames(clin_exp_inf),colnames(count))] # 按照顺序排列数据
ID_annoation <- ID_annoation[match(rownames(count),ID_annoation$gene_id),]
rownames(ID_annoation) <- NULL # 行名设为默认值
ID_annoation <- column_to_rownames(ID_annoation, "gene_id") # 基因id设置为行名

# 5.转换数据为指定矩阵、数据框
count <- as.matrix(count)
clin_exp_inf <- AnnotatedDataFrame(clin_exp_inf)
ID_annoation <- AnnotatedDataFrame(ID_annoation)

# 6.ExpressionSet构建
eset <- ExpressionSet(
  assayData = count,
  phenoData = clin_exp_inf,
  featureData = ID_annoation)

# 7.保存文件
save(eset, file = "expression_set.RData")

# 8.Expression Set展示
eset                # 总览
exprs(eset)         # 表达矩阵
pData(eset)         # 样本信息
fData(eset)         # 检测结果（注释信息）
